import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:get/get.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../app_views.dart';

/// 启动页控制器 - Splash Controller
///
/// 负责应用启动时的权限检查、数据加载和页面跳转
///nsible for permission checking, data loading and page navigation during app startup
class SplashLogic extends GetxController {
  /// 状态管理 - State management
  final SplashState state = SplashState();

  /// API仓库 - API repository
  final _apiRepository = Get.find<ApiRepository>();

  /// 倒计时定时器 - Countdown timer
  Timer? _countdownTimer;

  @override
  void onInit() {
    super.onInit();
    // _initializeState();
  }

  @override
  void onReady() {
    super.onReady();
    _checkPermissions();
  }

  @override
  void onClose() {
    _countdownTimer?.cancel();
    super.onClose();
  }

  /// 初始化状态 - Initialize state
  /// 设置启动页的初始状态
  /// Sets initial state for splash page
  // void _initializeState() {
  //   state.isLoading = false;
  //   state.progress = 0.0;
  //   state.statusMessage = '正在初始化...';
  //   state.isInitialized = false;
  //   state.countdown = 5;
  //   state.permissionGranted = false;
  //   state.showingDialog = false;
  //   state.isLoadingData = false;
  //   state.hasNetworkError = false;
  // }

  /// 开始倒计时 - Start countdown
  /// 权限检查通过后开始5秒倒计时
  /// Start 5-second countdown after permission check passes
  void _startCountdown() {
    state.countdown.value = 5;
    _countdownTimer = Timer.periodic(const Duration(seconds: 1), (timer) {
      if (state.countdown > 0) {
        state.countdown.value--;
      } else {
        timer.cancel();
        _loadRequiredData();
      }
    });
  }

  /// 检查权限 - Check permissions
  /// 检查应用所需的各种权限
  /// Check various permissions required by the app
  Future<void> _checkPermissions() async {
    try {
      // 检查通知权限 - Check notification permission
      final notificationStatus = await Permission.notification.status;

      // 检查网络权限（Android自动授予）- Check network permission (auto-granted on Android)
      // 在实际项目中可能需要检查其他权限 - May need to check other permissions in actual project

      if (notificationStatus.isDenied) {
        // 请求通知权限 - Request notification permission
        final result = await Permission.notification.request();
        if (result.isGranted) {
          state.permissionGranted.value = true;
          _startCountdown();
        } else {
          // 权限被拒绝，退出应用 - Permission denied, exit app
          SystemNavigator.pop();
        }
      } else {
        // 权限已授予 - Permission already granted
        state.permissionGranted.value = true;
        _startCountdown();
      }
    } catch (e) {
      debugPrint('权限检查失败: $e');
      // 权限检查失败时也继续执行，避免阻塞用户 - Continue execution even if permission check fails to avoid blocking user
      state.permissionGranted.value = true;
      _startCountdown();
    }
  }

  /// 加载必要数据 - Load required data
  /// 并行加载万年历数据和系统配置等必要数据
  /// Load calendar data and system configuration in parallel
  Future<void> _loadRequiredData() async {
    state.isLoadingData.value = true;
    state.hasNetworkError.value = false;

    try {
      // 并行加载多个数据源 - Load multiple data sources in parallel
      final results = await Future.wait([
        _loadCalendarData(),
        _loadSystemConfig(),
      ]);

      // 检查所有数据是否加载成功 - Check if all data loaded successfully
      final allSuccess = results.every((result) => result == true);

      if (allSuccess) {
        /// 标记初始化完成 - Mark initialization completed
        /// 更新状态为初始化完成
        /// Updates state to initialization completed
        state.progress.value = 1.0;
        state.statusMessage.value = '初始化完成';
        state.isInitialized.value = true;
        // 延迟一下再跳转，让用户看到完成状态 - Delay before navigation to let user see completion status
        await Future.delayed(const Duration(milliseconds: 500));
        _navigateToMainApp();
      } else {
        throw Exception('部分数据加载失败');
      }
    } catch (e) {
      debugPrint('数据加载失败: $e');
      state.errorMessage = '数据加载失败: $e';

      /// 显示网络错误对话框 - Show network error dialog
      /// 当网络请求失败时显示错误对话框
      /// Shows error dialog when network request fails
      state.showingDialog.value = true;
    } finally {
      state.isLoadingData.value = false;
    }
  }

  /// 加载万年历数据 - Load calendar data
  /// 获取今日万年历信息并存储到全局状态
  /// Gets today's calendar info and stores to global state
  Future<bool> _loadCalendarData() async {
    try {
      state.isLoading.value = true;
      state.progress.value = 0.5;
      state.statusMessage.value = '正在加载万年历数据...';
      state.isInitialized.value = false;

      final today = DateTime.now();
      final dateString =
          '${today.year}-${today.month.toString().padLeft(2, '0')}-${today.day.toString().padLeft(2, '0')}';
      final result = await _apiRepository.getCalendarInfo(dateString);

      if (result.success && result.data != null) {
        // 存储万年历数据到全局状态 - Store calendar data to global state
        debugPrint('万年历数据加载成功');
        return true;
      } else {
        throw Exception('万年历数据格式错误');
      }
    } catch (e) {
      debugPrint('加载万年历数据失败: $e');
      return false;
    }
  }

  /// 加载系统配置 - Load system configuration
  /// 获取应用配置信息
  /// Gets application configuration information
  Future<bool> _loadSystemConfig() async {
    try {
      state.progress.value = 0.8;
      state.statusMessage.value = '正在加载系统配置...';
      // 模拟配置加载 - Simulate configuration loading
      await Future.delayed(const Duration(milliseconds: 500));

      debugPrint('系统配置加载成功');
      return true;
    } catch (e) {
      debugPrint('加载系统配置失败: $e');
      return false;
    }
  }

  /// 重试数据加载 - Retry data loading
  /// 用户点击重试按钮时调用
  /// Called when user clicks retry button
  void retryLoading() {
    state.errorMessage = null;
    state.showingDialog.value = false;
    state.hasNetworkError.value = false;
    _loadRequiredData();
  }

  /// 跳过倒计时 - Skip countdown
  /// 用户点击跳过倒计时按钮时调用
  /// Called when user clicks skip countdown button
  void skipCountdown() {
    /// 跳过启动页 - Skip splash
    /// 用户点击跳过按钮时调用
    /// Called when user clicks skip button
    _countdownTimer?.cancel();
    _navigateToMainApp();
  }

  /// 导航到主应用 - Navigate to main app
  /// 启动页完成后跳转到主应用
  /// Navigate to main app after splash completion
  void _navigateToMainApp() {
    Get.offAllNamed('/root');
  }
}
